<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="85px"
    >
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择项目类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PROJECT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主办方" prop="organizer">
        <el-select
          v-model="queryParams.organizer"
          placeholder="请选择主办方"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PROJECT_ORGANIZER)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="其他主办方" prop="organizerOther">
        <el-input
          v-model="queryParams.organizerOther"
          placeholder="请输入其他主办方"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择级别" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PROJECT_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="第一作者" prop="author">
        <el-select
          v-model="queryParams.author"
          filterable
          remote
          reserve-keyword
          placeholder="请输入名字搜索"
          :remote-method="remoteSearch"
          :loading="userLoading"
          class="!w-240px"
          clearable
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="getUserDisplayName(item.id)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成员" prop="member" class="!w-[650px]">
        <el-select
          v-model="memberSelectValue"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入名字搜索"
          :remote-method="remoteSearch"
          :loading="userLoading"
          class="!w-[580px]"
          clearable
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="getUserDisplayName(item.id)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="立项时间" prop="projectStartTime">
        <el-date-picker
          v-model="queryParams.projectStartTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="结项时间" prop="projectEndTime">
        <el-date-picker
          v-model="queryParams.projectEndTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PROJECT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['digital:projects:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['digital:projects:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true">
      <el-table-column 
        label="项目名称" 
        align="center" 
        prop="name" 
        min-width="120"
        class-name="wrap-cell"
      >
        <template #default="scope">
          <div class="whitespace-normal break-words">{{ scope.row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" prop="type" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PROJECT_TYPE" :value="scope.row.type || ''" />
        </template>
      </el-table-column>
      <el-table-column label="主办方" align="center" min-width="120" class-name="wrap-cell">
        <template #default="scope">
          <div>
            <div v-if="scope.row.organizer">
              <dict-tag :type="DICT_TYPE.PROJECT_ORGANIZER" :value="scope.row.organizer || ''" :show-tag="false" />
            </div>
            <div v-if="scope.row.organizerOther">{{ scope.row.organizerOther }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="级别" align="center" prop="level" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PROJECT_LEVEL" :value="scope.row.level || ''" />
        </template>
      </el-table-column>
      <el-table-column label="成员及贡献率" align="center" min-width="250">
        <template #default="scope">
          <div 
            v-if="scope.row.member && scope.row.rate"
            class="whitespace-normal break-words"
          >
            <div 
              v-for="(member, index) in scope.row.member.split(',')" 
              :key="index"
              class="mb-1 last:mb-0"
            >
              {{ getUserNickname(member) }}: {{ scope.row.rate.split(',')[index] }}%
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="立项时间"
        align="center"
        prop="projectStartTime"
        :formatter="dateFormatterYMD"
        width="120"
      />
      <el-table-column
        label="结项时间"
        align="center"
        prop="projectEndTime"
        :formatter="dateFormatterYMD"
        width="120"
      />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PROJECT_STATUS" :value="scope.row.status || ''" />
        </template>
      </el-table-column>
      <el-table-column 
        label="佐证" 
        align="center" 
        prop="evidenceUrl" 
        min-width="150"
      >
        <template #default="scope">
          <div 
            v-if="scope.row.evidenceUrl && Array.isArray(scope.row.evidenceUrl)"
            class="flex flex-wrap justify-center gap-1"
          >
            <el-link
              v-for="(url, index) in scope.row.evidenceUrl"
              :key="index"
              type="primary"
              :href="url"
              target="_blank"
              :underline="false"
              class="inline-block"
            >
              佐证{{ index + 1 }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="160"
      />
      <!-- <el-table-column 
        label="备注" 
        align="center" 
        prop="remark" 
        min-width="120"
        show-overflow-tooltip
      /> -->
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['digital:projects:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['digital:projects:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProjectsForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { ref, onMounted, reactive, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import download from '@/utils/download'
import { ProjectsApi, ProjectsVO } from '@/api/digital/projects'
import ProjectsForm from './ProjectsForm.vue'
import * as UserApi from '@/api/system/user'

/** 项目 列表 */
defineOptions({ name: 'Projects' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 日期格式化（只显示日期）
const dateFormatterYMD = (row: any, column: any) => {
  if (!row[column.property]) {
    return ''
  }
  const date = new Date(row[column.property])
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const loading = ref(true) // 列表的加载中
const list = ref<ProjectsVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  type: undefined,
  organizer: undefined,
  organizerOther: undefined,
  level: undefined,
  author: undefined,
  member: undefined,
  rate: undefined,
  projectStartTime: [],
  projectEndTime: [],
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 成员选择的内部值
const memberSelectValue = ref([])

// 监听memberSelectValue变化，更新queryParams.member
watch(memberSelectValue, (newVal) => {
  queryParams.member = newVal.join(',')
}, { deep: true })

// 用户映射
const userMap = ref<Record<string, any>>({})
const userLoading = ref(false)
const userOptions = ref([])

// 初始化用户列表
const initUserOptions = async () => {
  try {
    const data = await UserApi.getAllUser()
    userOptions.value = data
    // 更新用户映射
    data.forEach(user => {
      userMap.value[user.id] = user
    })
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 远程搜索用户
const remoteSearch = async (query: string) => {
  if (query !== '') {
    userLoading.value = true
    try {
      userOptions.value = userOptions.value.filter(item => 
        item.username.toLowerCase().includes(query.toLowerCase()) ||
        (item.nickname && item.nickname.toLowerCase().includes(query.toLowerCase()))
      )
    } finally {
      userLoading.value = false
    }
  } else {
    // 当搜索词为空时，显示所有用户
    await initUserOptions()
  }
}

// 获取用户显示名称
const getUserDisplayName = (userId) => {
  const user = userMap.value[userId]
  if (user) {
    return `${user.username}${user.nickname ? ` (${user.nickname})` : ''}`
  }
  return ''
}

// 获取用户昵称
const getUserNickname = (userId: string) => {
  return userMap.value[userId]?.nickname || userId
}

// 处理查询参数
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置查询参数
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.pageNo = 1
  queryParams.member = undefined
  memberSelectValue.value = []
  getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProjectsApi.getProjectsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProjectsApi.deleteProjects(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('删除失败:', error)
    message.error(t('common.delFail'))
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProjectsApi.exportProjects(queryParams)
    download.excel(data, '项目.xls')
  } catch (error) {
    console.error('导出失败:', error)
    message.error(t('common.exportFail'))
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await initUserOptions()
  getList()
  if (queryParams.member) {
    memberSelectValue.value = queryParams.member.split(',')
  }
})
</script>

<style lang="scss" scoped>
:deep(.wrap-cell) {
  .cell {
    white-space: normal !important;
    line-height: 1.5;
    padding: 8px;
  }
}

.whitespace-normal {
  white-space: normal;
}

.break-words {
  word-wrap: break-word;
  word-break: break-word;
}
</style>
